package com.m3839.sdk.pay.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.m3839.sdk.common.base.BaseDialogFragment;
import com.m3839.sdk.common.base.SimpleViewHolder;
import com.m3839.sdk.common.core.ApiError;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.core.ErrorConstant;
import com.m3839.sdk.common.event.SubjectBus;
import com.m3839.sdk.common.util.AppUtils;
import com.m3839.sdk.common.util.FastClickUtils;
import com.m3839.sdk.common.util.NetworkUtils;
import com.m3839.sdk.common.util.ToastUtil;
import com.m3839.sdk.login.HykbUser;
import com.m3839.sdk.login.core.LoginManager;
import com.m3839.sdk.pay.bean.OrderInfo;
import com.m3839.sdk.pay.bean.PayChannel;
import com.m3839.sdk.pay.bean.PayConfig;
import com.m3839.sdk.pay.bean.PayInfo;
import com.m3839.sdk.pay.bean.PayLimit;
import com.m3839.sdk.pay.bean.PayResult;
import com.m3839.sdk.pay.constant.PayConstant;
import com.m3839.sdk.pay.platform.PayResultCallBack;
import com.m3839.sdk.pay.platform.PayWrapper;
import com.m3839.sdk.pay.platform.alipay.AlipayWrapper;
import com.m3839.sdk.pay.platform.wechat.WechatPayWrapper;
import com.m3839.sdk.pay.task.PayTask;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Description:该对话框是用来显示支付的结果
 *
 * @author 陈宝阳
 * @create 2020/8/6 10:10
 */
public class PayDialogFragment extends BaseDialogFragment {

  /** 支付渠道的列表适配器 */
  private PayChannelsAdapter adapter;

  /** 支付信息 */
  private PayInfo payInfo;
  /** 支付配置 */
  private PayConfig payConfig;

  private PayWrapper payWrapper;

  private String payChannel;

  /** 平台的订单ID */
  private String orderId;

  /**
   * 用来标识当前页面是否被销毁了，防止被销毁之后，还在请求数据占用资源
   */
  private boolean isDestroyed = false;

  private PayTask payTask;

  public static PayDialogFragment getInstance(PayInfo payInfo, PayConfig payConfig) {
    PayDialogFragment fragment = new PayDialogFragment();
    Bundle data = new Bundle();
    data.putParcelable(PayConstant.HYKB_KEY_PAY_CONFIG, payConfig);
    data.putParcelable(PayConstant.HYKB_KEY_PAY_INFO, payInfo);
    fragment.setArguments(data);
    return fragment;
  }

  @Override
  protected void parseArgs() {
    payInfo = getArguments().getParcelable(PayConstant.HYKB_KEY_PAY_INFO);
    payConfig = getArguments().getParcelable(PayConstant.HYKB_KEY_PAY_CONFIG);
  }

  public void setPayTask(PayTask payTask) {
    this.payTask = payTask;
  }

  @Override
  protected String getLayoutName() {
    return "hykb_pay_dialog_fragment";
  }

  @Override
  protected void initView(View view) {
    // 刚打开页面是显示支付列表，隐藏支付加载中的UI
    viewHolder.setViewVisible("ll_open_loading", false);
  }

  @Override
  protected void setContent() {
    if (payInfo != null) {
      viewHolder.setTextView("tv_goods_name",payInfo.goodsName);
      viewHolder.setTextView("tv_pay_money",
              String.format(PayConstant.HYKB_STRING_MONEY_FORMAT, payInfo.money));

      // 支付渠道列表设置适配器
      adapter = new PayChannelsAdapter(getActivity(), getPayChannels());
      viewHolder.setListAdapter("lv_pay_channels", adapter);
    }
  }

  private List<PayChannel> getPayChannels() {
    List<PayChannel> channels = new ArrayList<>();
    if (payConfig != null && payConfig.payChannels != null) {
      for (int i = 0; i < payConfig.payChannels.size(); i++) {
        String channelValue = payConfig.payChannels.get(i);
        // 微信H5的支付方式
        if(PayConstant.HYKB_VALUE_PAY_CHANNEL_WECHAT_H5.equals(channelValue)) {
          PayChannel payChannel = new PayChannel("hykb_icon_pay_channel_wechat",
                  PayConstant.HYKB_STRING_PAY_CHANNEL_WECHAT, channelValue);
          channels.add(payChannel);

        }else
          //支付宝的支付方式
          if(PayConstant.HYKB_VALUE_PAY_CHANNEL_ALIPAY.equals(channelValue)) {
          PayChannel payChannel = new PayChannel("hykb_icon_pay_channel_alipay",
                  PayConstant.HYKB_STRING_PAY_CHANNEL_ALIPAY, channelValue);
          channels.add(payChannel);
        }
      }

      //设置默认选择第一项支付方式
      if (channels.size() > 0) {
        channels.get(0).select = true;
      }
    }

    return channels;
  }

  @Override
  protected void initListener() {

    //支付按钮事件：下单
    viewHolder.setViewClick("tv_pay_btn",new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        PayChannel payChannel = adapter.getSelectPayChannel();
        //判断是不是选择了微信支付方式，如果是，检测是否有安装微信
        if (!AppUtils.isWeChatAvailable(getActivity())
            && payChannel != null
            && TextUtils.equals(payChannel.payChannelValue,
            PayConstant.HYKB_VALUE_PAY_CHANNEL_WECHAT_H5)) {
          ToastUtil.showToast(getActivity(),"您尚未安装微信，请先安装或选择其他支付方式");
          return;
        }

        if (FastClickUtils.isFastDoubleClick()) {
          return;
        }

        if (!NetworkUtils.isConnected(getActivity())) {
          ToastUtil.showToast(getActivity(), ErrorConstant.ERR_MSG_NETWORK_ERROR);
          return;
        }

        //显示是打开某个支付方式的加载，隐藏住支付渠道列表
        viewHolder.setViewVisible("ll_pay_channels", false);
        viewHolder.setViewVisible("ll_open_loading", true);

        if (payChannel != null) {
          viewHolder.setTextView("tv_open_desc",
                  String.format(PayConstant.HYKB_STRING_OPEN_PAY_CHANNEL_FORMAT,
                          payChannel.payChannelName));
          submitOrder(payChannel);
        }
      }
    });

    // 弹窗关闭按钮事件
    viewHolder.setViewClick("iv_pay_close", new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        PayResult result = new PayResult();
        result.payInfo = payInfo;
        result.resultCode = ErrorConstant.HYKB_CODE_PAY_DIALOG_CLOSE;
        result.message = ErrorConstant.ERR_MSG_PAY_DIALOG_CLOSE;
        payTask.handlePayCallBack(result);
        dismiss();
      }
    });
  }

  /**
   * 下单
   *
   * @param payChannel 支付渠道信息{@link PayChannel}
   */
  private void submitOrder(PayChannel payChannel) {
    HykbUser user = LoginManager.getInstance().getUser();
    if (user == null) {
      return;
    }

    if (payInfo == null) {
      return;
    }

    SubjectBus.get().observe(Constant.HYKB_EVENT_PAY_ORDER, new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        OrderInfo orderInfo = (OrderInfo) arg;
        orderId = orderInfo.orderId;
        openThirdPartyPay(orderInfo);
      }
    });

    SubjectBus.get().observe(Constant.HYKB_EVENT_PAY_LIMIT, new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        dismiss();
        payTask.getPayUiController().showPayLimitDialog(getActivity(), payTask, (PayLimit) arg, payInfo);
      }
    });

    SubjectBus.get().observe(Constant.HYKB_EVENT_PAY_ORDER_FAILED, new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        ApiError apiError = (ApiError) arg;
        if(apiError == null) {
          return;
        }
        if (apiError.code == Constant.HYKB_CODE_USER_ROBBED) {
          payTask.handleUserRobbed(apiError.message);
          dismiss();
        } else {
          if (NetworkUtils.isConnected(getActivity())) {
            PayResult result = new PayResult();
            result.payInfo = payInfo;
            result.resultCode = apiError.code;
            result.message = apiError.message;
            payTask.handlePayCallBack(result);
            ToastUtil.showToast(getActivity(), apiError.message);
            dismiss();
          } else {
            ToastUtil.showToast(getActivity(), ErrorConstant.ERR_MSG_NETWORK_ERROR);
          }
        }
      }
    });

    //服务端下单操作，获取三方支付的相关配置
    payTask.getPayModel().submitOrder(payInfo.cpOrderId, user.getNick(), payInfo.money,
        payInfo.goodsName, payInfo.server, payInfo.ext, payChannel.payChannelValue);
  }

  /**
   * 打开第三方支付
   *
   * @param orderInfo 订单信息{@link OrderInfo}
   */
  private void openThirdPartyPay(OrderInfo orderInfo) {
    payChannel = orderInfo.payType;
    if (TextUtils.equals(orderInfo.payType, PayConstant.HYKB_VALUE_PAY_CHANNEL_WECHAT_H5)) {
      payWrapper = new WechatPayWrapper();
    } else if (TextUtils.equals(orderInfo.payType, PayConstant.HYKB_VALUE_PAY_CHANNEL_ALIPAY)) {
      payWrapper = new AlipayWrapper();
    }

    if(isDestroyed) {
      //当前界面如果已经被销毁，直接跳过，不打开第三方支付
      return;
    }

    if (payWrapper != null) {
      payWrapper.doPay(getActivity(), orderInfo, new PayResultCallBack() {

        @Override
        public void onResult(boolean success, String status, String resultInfo) {
          //暂时做个判断处理, 提交中，需要SDK去做轮询查询订单
          if (TextUtils.equals(status, WechatPayWrapper.HYKB_WECHATH5_CODE_SUBMIT)) {
            viewHolder.setTextView("tv_open_desc",resultInfo);
            payTask.startPollingOrder(orderId);
            return;
          }
          // 直接支付成功，返回
          handlePayResult(Integer.parseInt(status), resultInfo);
        }
      });
    }
  }

  /**
   * 支付结果返回
   *
   * @param code          支付结果code
   * @param resultInfo    支付结果提示内容
   */
  private void handlePayResult(int code, String resultInfo) {
    //支付结果日志上报
    payResultReport(code, resultInfo);

    PayResult result = new PayResult();
    result.payInfo = payInfo;
    result.resultCode = code;
    result.message = resultInfo;
    result.payChannel = payChannel;
    result.orderId = orderId;
    payTask.showPayResultDialog(result);
    dismissAllowingStateLoss();
  }

  /**
   * 日志上报
   *
   * @param code 支付结果code
   * @param msg  支付结果信息
   */
  private void payResultReport(int code, String msg) {
    String content = code == Constant.HYKB_CODE_SUCCESS ? "ok" : msg;
    payTask.getPayModel().payReport(orderId, content);
  }

  @Override
  public void onDestroy() {
    isDestroyed = true;
    super.onDestroy();
  }
}
